import { View } from "@tarojs/components";
import { GStyleSheet } from "@/utils/DarkMode";
import { memo, useCallback, useState } from "react";
import { FC } from "@tarojs/taro";
import { useUpdateEffect } from "@/hooks/useUpdateEffect";

const dstyle = GStyleSheet.create({
  switch: {
    position: "relative",
    boxSizing: "border-box",
    width: 46,
    height: 23,
    borderRadius: 13,
    padding: 2,
    transition: "all 0.2s",
  },
  block: {
    width: 19,
    height: 19,
    borderRadius: "100%",
    transition: "all 0.2s",
  },
  disabled: {
    position: "absolute",
    left: 0,
    top: 0,
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(255,255,255, 0.7)",
    borderRadius: 13,
  },
});

interface IProps {
  checked?: boolean;
  disabled?: boolean;
  onChange?: (checked: boolean) => void;
  trackColor?: string;
  activeColor?: string;
  blockColor?: string;
}

const Switch: FC<IProps> = ({
  checked = false,
  disabled = false,
  trackColor = "#EBEBEB",
  activeColor = "#007AFF",
  blockColor = "#fff",
  onChange,
}) => {
  const [val, setVal] = useState(checked);
  const styles = dstyle.useDynamicStyle();

  useUpdateEffect(() => {
    setVal(checked)
  }, [checked])

  const handleChange = useCallback((e) => {
    e.stopPropagation()
    setVal(!val);
    onChange?.(!val);
  }, [val, onChange]);

  return (
    <View
      style={{
        ...styles.switch,
        backgroundColor: val ? activeColor : trackColor,
      }}
      onClick={disabled ? undefined : handleChange}
    >
      <View
        style={{
          ...styles.block,
          backgroundColor: blockColor,
          transform: `translateX(${val ? "120" : "0"}%)`,
        }}
      ></View>
      { disabled && <View style={styles.disabled}></View> }
    </View>
  );
};

export default memo(Switch);
